using System.Text;
using System.Text.RegularExpressions;
using welog.core;

namespace welog.plugin;

public class AutoSyncYesterdayIncompleteTasks:IWelogTextPlugin
{
    public string Name { get; set; } = "AutoSyncTask";
    
    public string Description { get; set; } = "自动同步前一天未完成任务";

    private SysConfig _sysConfig;
    
    public void Config(SysConfig sysConfig)
    {
        _sysConfig = sysConfig;
    }

    public string Create(string logContent,string yesterdayFilePath)
    {
        this.ReplaceContentWithSummary(yesterdayFilePath,logContent);
        
        return logContent;
    }

    public string Save(string logContent)
    {
        return logContent;
    }
    
    private void ReplaceContentWithSummary(string sourceFilePath, string targetFilePath)
    {
        // 创建一个StringBuilder来累积要替换@@@1的内容
        var summaryBuilder = new StringBuilder();

        // 打开源文件并逐行读取
        using (var reader = new StreamReader(sourceFilePath))
        {
            string line;
            var lastTime = Path.GetFileNameWithoutExtension(sourceFilePath);
            while ((line = reader.ReadLine()) != null)
            {
                // 使用正则表达式检查当前行是否包含"进行中"或"未开始"
                if (Regex.IsMatch(line, @"进行中|未开始"))
                {
                    // 如果匹配，将该行添加到summaryBuilder中
                    var res = UpdateData(line, lastTime);
                    summaryBuilder.AppendLine(res);
                }
            }
        }

        // 读取目标文件内容
        string targetContent;
        using (var reader = new StreamReader(targetFilePath))
        {
            targetContent = reader.ReadToEnd();
        }

        // 替换目标文件中@@@1位置的内容
        string updatedContent = targetContent.Replace("|@@@1", summaryBuilder.ToString().TrimEnd('\r','\n'));

        // 将替换后的内容写回目标文件
        using (var writer = new StreamWriter(targetFilePath))
        {
            writer.Write(updatedContent);
        }
    }

    /// <summary>
    /// 更新每一行记录
    /// </summary>
    /// <param name="line">行内容</param>
    /// <param name="lastTime">行日期</param>
    /// <returns></returns>
    private string UpdateData(string line,string lastTime)
    {
        var items = line.Split("|");
        if (items.Length == 14)
        {
            if(string.IsNullOrWhiteSpace(items[11]))
            {
                items[11] = lastTime;
            }

            if (!string.IsNullOrWhiteSpace(items[9]))
            {
                if (!string.IsNullOrWhiteSpace((items[10])))
                {
                    items[10] = (Convert.ToDouble(items[10]) + Convert.ToDouble(items[9])).ToString();
                    items[9] = string.Empty;
                }
                else
                {
                    items[10] = items[9];
                    items[9] = string.Empty;
                }
            }

            return $"{string.Join('|',items)}";
        }
        else
        {
            return line;
        }
    }
}